#!/usr/bin/env python3
"""
Script to recreate the OpenMemory collection with updated vector dimensions.
This script will reset the memory client to recreate the collection with the new 1024-dimensional vectors.
"""

import sys
import os
import logging
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "openmemory" / "api"))

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def recreate_openmemory_collection():
    """
    Recreate the OpenMemory collection with updated vector dimensions.
    """
    try:
        # Import after setting up the path
        from app.utils.memory import get_memory_client, reset_memory_client
        
        logger.info("Starting collection recreation process...")
        
        # Reset the memory client to clear any cached instances
        logger.info("Resetting memory client...")
        reset_memory_client()
        
        # Get a fresh memory client with the new configuration
        logger.info("Initializing new memory client with updated configuration...")
        memory_client = get_memory_client()
        
        if memory_client is None:
            logger.error("Failed to initialize memory client")
            return False
        
        # Reset the memory client to recreate the collection
        logger.info("Resetting memory store to recreate collection with new dimensions...")
        memory_client.reset()
        
        logger.info("Collection recreation completed successfully!")
        logger.info("The OpenMemory collection now uses 1024-dimensional vectors.")
        return True
        
    except ImportError as e:
        logger.error(f"Import error: {e}")
        logger.error("Make sure you're running this script from the project root directory")
        return False
    except Exception as e:
        logger.error(f"Error during collection recreation: {e}")
        return False

def main():
    """
    Main function to execute the collection recreation.
    """
    logger.info("OpenMemory Collection Recreation Script")
    logger.info("=======================================")
    logger.info("This script will recreate the OpenMemory collection with 1024-dimensional vectors.")
    logger.info("WARNING: This will delete all existing memories in the collection!")
    
    # Ask for confirmation
    try:
        confirmation = input("\nDo you want to continue? (yes/no): ").strip().lower()
        if confirmation not in ['yes', 'y']:
            logger.info("Operation cancelled by user.")
            return
    except KeyboardInterrupt:
        logger.info("\nOperation cancelled by user.")
        return
    
    # Perform the recreation
    success = recreate_openmemory_collection()
    
    if success:
        logger.info("\n✅ Collection recreation completed successfully!")
        logger.info("The OpenMemory collection is now ready to use with 1024-dimensional vectors.")
    else:
        logger.error("\n❌ Collection recreation failed. Please check the logs above for details.")
        sys.exit(1)

if __name__ == "__main__":
    main()